<?php

class My_Acl{
    public function hasIdentity($request){
        //die("Hệ thống đang bảo trì. Vui lòng quay lại sau.");
        $helper_redirector = new Zend_Controller_Action_Helper_Redirector();
        $auth = Zend_Auth::getInstance();
       
        $auth->setStorage(new Zend_Auth_Storage_Session('Zend_Auth_KPI')); 
        if(!$auth->hasIdentity()){
            $helper_redirector->gotoUrl('/default/auth');
        }
          
        return $auth;
    }
    
    // kiem tra user duoc quyen truy cap tinh nang nay ko
    public function checkAllowed($request){
        
        
        $helper_redirector = new Zend_Controller_Action_Helper_Redirector();
        $auth = Zend_Auth::getInstance();
        
        $auth->setStorage(new Zend_Auth_Storage_Session('Zend_Auth_KPI')); 
        if ($auth->hasIdentity()){
        
            //history
            $requestUri = $request->getRequestUri();
            $module     = $request->getModuleName();
            $controller = $request->getControllerName();
            $action     = $request->getActionName();
            $user       = $auth->getIdentity();
            $requestUri = $request->getRequestUri();
            //default/user/index
            
            if(!$this->isAllowed($auth->getIdentity(), $request)){
                $helper_redirector->gotoUrl('/default/error/accessdenied');
            }
        }else{
            $helper_redirector->gotoUrl('/default/auth');
        }
        return $auth;
    }
    
    public function isAllowed($user, $request){
        $db = Zend_Db_Table::getDefaultAdapter();
        // lấy danh sách các resource của user 
        $query = $db->select()
                    ->from(array('p'=>'role'), array('p.roleId', 'p.partnerId', 'p.resourceId'))
                    ->where('p.roleId IN (SELECT u.roleId FROM user_role u WHERE u.userId = '.$user['userId'].')');
        $privilegeList   = $db->fetchAll($query);
        $resourceTemp   = array();
        $partnerTemp       = array();
        foreach($privilegeList as $row){
            if($row['resourceId'])
            $resourceTemp   = array_merge($resourceTemp, json_decode($row['resourceId']));
            if($row['partnerId'])
                $partnerTemp       = array_merge($partnerTemp, json_decode($row['partnerId']));
        }
        $resourceTemp           = array_unique($resourceTemp);
        $resourceList           = array_values($resourceTemp);
        $partnerTemp               = array_unique($partnerTemp);
        $partnertList               = array_values($partnerTemp);
  
        // kiem tra co request xem trang game ko. 
       // if($request->getModuleName() == 'default'){
//            $game = $request->getParams();
//          
//            if(isset($game['partnerId'])){
//                if(!in_array($game['partnerId'], $partnertList)){
//                    return false;
//                }
//            }else{
//                return false;
//            }
//        } 
        // kiểm tra request của user thuộc resource nào
        $module     = $request->getModuleName();
        $controller = $request->getControllerName();
        $action     = $request->getActionName();
        $query = $db->select()
                    ->from(array('r'=>'resource'), array('r.resourceId'))
                    ->where("r.menu = '$module/$controller/$action'");
        $resourceCheck = $db->fetchRow($query);
      
        // kiểm tra request của user có nằm trong danh sách các resource của user ko (kt có quyền thao tác trên request này ko)
        if(in_array($resourceCheck['resourceId'], $resourceList) || !isset($resourceCheck['resourceId']))
            return true;
        else
            return false;
    }
	
    // danh sach quyen cua user
	public function listAllowed($user, $partnerId = 0){
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        // Lấy danh sách các resource của user (json)
        if($partnerId){
            $query = $db->select()
                        ->from(array('p'=>'role'), array('p.roleId', 'p.resourceId'))
                        ->where('p.partnerId like "%'.$partnerId.'%" AND p.roleId IN (SELECT u.roleId FROM user_role u WHERE u.userId = '.$user['userId'].')');
                   
            $resourceList = $db->fetchAll($query);
        }else{
            $query = $db->select()
                        ->from(array('p'=>'role'), array('p.roleId', 'p.resourceId'))
                        ->where('p.roleId IN (SELECT u.roleId FROM user_role u WHERE u.userId = '.$user['userId'].')');
            $resourceList = $db->fetchAll($query);
        }
        
        $resourceTemp = array();
        foreach($resourceList as $row){
            $resourceTemp = array_merge($resourceTemp, json_decode($row['resourceId']));
        }
        $resourceTemp           = array_unique($resourceTemp);//loai bo cac phan tu trung trong mang
        $resourceList           = array_values($resourceTemp);//lay lai gia tri trong mang 1 cach lien tuc
        $resourceList           = json_encode($resourceList);////bien mang thanh kieu json

        $resourceList           = str_replace(array('[',']'), array('(',')'), $resourceList);
        $query = $db->select()
                    ->from(array('r'=>'resource'), array('r.resourceId','r.resourceName','r.moduleName','r.controllerName','r.actionName','r.menu'))
                    ->where('r.resourceId IN '.$resourceList)
                    ->order('r.resourceId ASC');
                                 
		$row = $db->fetchAll($query);
		return $row;
    }
    
    // danh sach quyen cua user
	public function checkResource($user, $module, $controller, $action){
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        
        // Lấy danh sách các resource của user (json)
        $query = $db->select()
                    ->from(array('p'=>'role'), array('p.roleId', 'p.resourceId'))
                    ->where('p.roleId IN (SELECT u.roleId FROM user_role u WHERE u.userId = '.$user['userId'].')');
        $resourceList = $db->fetchAll($query);
        $resourceTemp = array();
        foreach($resourceList as $row){
            $resourceTemp = array_merge($resourceTemp, json_decode($row['resourceId']));
        }
        $resourceTemp           = array_unique($resourceTemp);
        $resourceList           = array_values($resourceTemp);
        $resourceList           = json_encode($resourceList);
        $resourceList           = str_replace(array('[',']'), array('(',')'), $resourceList);
        //echo '<pre>',print_r($resourceList),'</pre>';exit;
        
        // Lấy danh sách các resource của user (record)
        $query = $db->select()
                    ->from(array('r'=>'resource'), array('r.resourceId','r.moduleName','r.controllerName','r.actionName'))
                    ->where('r.resourceId IN '.$resourceList)
                    #->where('r.menu = ?',"$module/$controller/$action")
                    ->where('r.moduleName = ?',$module)
                    ->where('r.controllerName = ?',$controller)
                    ->where('r.actionName = ?',$action);
                    
		$row = $db->fetchRow($query);
        if($row)
		  return true;
		return false;
    }
    
    // kiem tra chuc nang duoc bao tri hay khong
    public function checkRepair($request, $repair = ''){
        $helper_redirector = new Zend_Controller_Action_Helper_Redirector();
        $auth = Zend_Auth::getInstance();
        
        $module     = $request->getModuleName();
        $controller = $request->getControllerName();
        $action     = $request->getActionName();
        
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $query = $db->select()
                    ->from(array('r'=>'resource'), array('r.resourceId','r.moduleName','r.controllerName','r.actionName'))
                    #->where('r.menu = ?',"$module/$controller/$action")
                    ->where('r.moduleName = ?',$module)
                    ->where('r.controllerName = ?',$controller)
                    ->where('r.actionName = ?',$action);
                    
		$row = $db->fetchRow($query);
        
        if(!$row){
            return false;//khong bao tri
        }else{
            $repair = json_decode($repair);
            if(is_array($repair) && in_array($row['resourceId'], $repair)){
                return true;
            }else{
                return false;
            }
        }
        
    }
    
}
